package main

import (
	"bufio"
	"flag"
	"fmt"
	"net"
	"os"
)

var (
	host = flag.String("h", "", "host ip address")
	port = flag.String("p", "", "host port")
	quit chan bool
)

func read(conn net.Conn) {
	data := make([]byte, 2048)
	for {
		n, err := conn.Read(data)
		if err != nil {
			fmt.Println("socket closed")
			quit <- true
			return
		}
		fmt.Println(string(data[:n]))
		go waitinput(conn)
	}
}

func send(conn net.Conn, cmd string) {
	conn.Write([]byte(cmd))
}

func waitinput(conn net.Conn) {
	reader := bufio.NewReader(os.Stdin)

	fmt.Print("cmd>")
	input, _, _ := reader.ReadLine()
	cmd := string(input)
	if cmd == "quit" {
		quit <- true
		return
	}
	go send(conn, cmd)

}

func connect(host, port, pwd string) {
	addr := fmt.Sprintf("%s:%s", host, port)
	conn, err := net.Dial("tcp", addr)

	if err != nil {
		fmt.Println(err)
		return
	}
	defer conn.Close()

	quit = make(chan bool)
	conn.Write([]byte(fmt.Sprintf("connect %s", pwd)))
	go read(conn)

	select {
	case <-quit:
		break
	}

}

func main() {

	flag.Parse()
	if *host == "" || *port == "" {
		fmt.Println("useage:tc -h 127.0.0.1 -p 3456")
		flag.PrintDefaults()
		return
	}

	reader := bufio.NewReader(os.Stdin)
	fmt.Print("password:")
	pass, _, _ := reader.ReadLine()

	connect(*host, *port, string(pass))

}
